package org.web.demo.common.util;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * IP工具类，其实主要是用来学习各类请求头的
 *
 * @author yexi
 */
public class IpUtil {

    /**
     * 获取请求IP地址
     *
     * @param request
     * @return
     */
    public static String getRemoteAddress(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Real-IP");
        // X-Forwarded-For是一个 Squid 开发的字段，只有在通过了HTTP代理或者负载均衡服务器时才会添加该项。
        // 格式为X-Forwarded-For:client1,proxy1,proxy2，一般情况下，第一个ip为客户端真实ip，后面的为经过的代理服务器ip。现在大部分的代理都会加上这个请求头。
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("x-forwarded-for");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            // 经过apache http服务器的请求才会有，用apache http做代理时一般会加上Proxy-Client-IP请求头。
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            // WL-Proxy-Client-IP是他的weblogic插件加上的头。
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            // 有些代理服务器也会加上HTTP_CLIENT_IP请求头。
            ipAddress = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            // nginx代理一般会加上X-Real-IP请求头
            ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        // 若实在获取不到时，就采用最原始的getRemoteAddr()方法来获取
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                    ipAddress = inet.getHostAddress();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                    return "127.0.0.1";
                }
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP地址，其后的为代理IP，多个IP按照','分割
        if (ipAddress != null) {
            String[] split = ipAddress.split(",");
            if (1 < split.length) {
                ipAddress = split[0];
            }
        }
        return ipAddress;
    }

}



